package com.woniuxy.shirotest;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

public class MyRealm extends AuthorizingRealm {
    /**
     * 授权用 授权信息
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String primaryPrincipal = principals.getPrimaryPrincipal()+"";
        System.out.println(primaryPrincipal);
        //1.模拟去数据库中找一下 我这个校长所拥有的角色和权限
        Set<String> list =new HashSet<>();
        list.add("role1");
        list.add("role2");
        list.add("role3");
        HashSet<String> hashSet = new HashSet<>();
        hashSet.add("user:add");
        hashSet.add("user:delete");
        hashSet.add("user:update");
        hashSet.add("user:find");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles((Set<String>) list);
        simpleAuthorizationInfo.setStringPermissions(hashSet);
        return simpleAuthorizationInfo;
    }

    /**
     * 认证信息
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        1.简单的账号密码登录
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        char[] s = usernamePasswordToken.getPassword();
        String password = new String(s);
        if(username.equals("mayuhang")){
            if(password.equals("654321")){
                return new SimpleAuthenticationInfo(username,password,"myRealm");
            }else{
                throw new RuntimeException("密码错误");
            }
        }else{
            throw new RuntimeException("账号错误");
        }
    }
}
